package com.sanji.sjmallmodule.phoneshell;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.sanji.sjmallapp.MallApplication;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallmodule.goods.BaseFrament;
import com.sanji.sjmallmodule.order.FirmOrderActivity;
import com.sanji.sjmallutils.Tools;
import com.sanji.sjmallwidget.MyGrideView;
import com.sanji.sjmallwidget.XListView;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.helper.StringUtil;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/9/7.
 */

public class PhoneShellFragment extends BaseFrament implements View.OnClickListener, NoHttpListener, XListView.IXListViewListener, AdapterView.OnItemClickListener {

    @BindView(R.id.common_left_tv)
    TextView titleTv;
    @BindView(R.id.phone_shell_select)
    LinearLayout filterLayout;
    @BindView(R.id.phone_shell_select_arrow)
    ImageView arrowImg;
    @BindView(R.id.phone_shell_model_tv)
    TextView modelTv;
    @BindView(R.id.phone_shell_material_quality_tv)
    TextView materialQualityTv;
    @BindView(R.id.phone_shell_technics_tv)
    TextView technicsTv;
    @BindView(R.id.phone_shell_list)
    XListView listView;

    private MyGrideView brandGridView;
    private TextView modelTitleTv;
    private MyGrideView modelGridView;
    //工艺
    private MyGrideView propertyGridView;
    //材质
    private MyGrideView materialGridView;

    //标志位 标志已经初始化完成
    private boolean isPrepared;


    private View rootView;
    private PopupWindow filterPop;
    private int popHeight;
    private String brandUrl = "";
    private String goodsUrl = "";
    private Request<JSONArray> cagyRequest;
//    private Request<JSONObject> goodsRequest;
    private int page = 0;
    private int size = 10;
    private String uid;

    //是否为品牌请求
    private int categoryId = 1;
    private List<PhoneShellBrandBean> brandList = new ArrayList<>();
    private Map<Integer, List<PhoneShellBrandBean>> modelMap = new HashMap<>();
    private List<PhoneShellBrandBean> modelList;
    private String categoryNum = "";
    private String categoryName = "全部";
    private String sc_material = "";
    private String sc_technology = "";

    private PhoneShellBrandAdapter brandAdapter;
    private PhoneShellBrandAdapter modelAdapter;
    private boolean refresh = false;
    private List<ShellGoodsBean> goodsList = new ArrayList<>();
    private PhoneShellAdapter goodsAdapter;
    //工艺、材质
    private String propertyUrl = "";
    private List<PropertyBean> materialList = new ArrayList<>();
    private List<PropertyBean> technologyList = new ArrayList<>();
    private ShellPropertyAdapter materialAdapter;
    private ShellPropertyAdapter propertyAdapter;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        popHeight = MallApplication.myShare.getInt(ConfigConts.ScreenHight, 800) * 7 / 10;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_phone_shell, null);
            ButterKnife.bind(this, rootView);
            isPrepared = true;
            initView();
            lazyLoadData();
        }
        return rootView;
    }

    @Override
    public void lazyLoadData() {
        if (!isPrepared || !isVisible) {
            return;
        }
        //查询所有品牌
        if (brandList.size() == 0) {
            categoryId = 1;
            requestBrandData();
        }
        if (technologyList.size() == 0) {
            //查询工艺
            reqProperty("");
        }
        if (goodsList.size() == 0) {
            requestGoods();
        }

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

//        initData();
    }

    private void initView() {
        titleTv.setText("小千定制");
        filterLayout.setOnClickListener(this);
        listView.setXListViewListener(this);
        listView.setOnItemClickListener(this);
        uid = MallApplication.myShare.getString(ConfigConts.USER_ID, "");


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.phone_shell_select:
                shellFilterPopWindow();
                break;
            case R.id.pop_shell_submit_tv:
                filterPop.dismiss();

                modelTv.setText(categoryName);
                materialQualityTv.setText(sc_material);
                technicsTv.setText(sc_technology);

                refresh = true;
                requestGoods();
                break;
        }
    }

    /**
     * 条件筛选
     */
    public void shellFilterPopWindow() {
        Tools.backgroundAlpaha(getActivity(), 0.6f);
        if (filterPop == null) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.pop_shell_filter, null);
            brandGridView = (MyGrideView) view.findViewById(R.id.pop_shell_brand_grid_view);
            modelTitleTv = (TextView) view.findViewById(R.id.pop_shell_model_title_tv);
            modelGridView = (MyGrideView) view.findViewById(R.id.pop_shell_model_grid_view);
            filterPop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, popHeight);
            filterPop.setBackgroundDrawable(new ColorDrawable());
            filterPop.setOutsideTouchable(true);
            filterPop.setFocusable(true);
            filterPop.setAnimationStyle(R.style.my_popwindow_left_anim_style);
            filterPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    Tools.backgroundAlpaha(getActivity(), 1.0f);
                }
            });
            brandGridView.setOnItemClickListener(brandItemClick);
            modelGridView.setOnItemClickListener(modelItemClick);
            view.findViewById(R.id.pop_shell_submit_tv).setOnClickListener(this);
//            ((RadioGroup) view.findViewById(R.id.pop_shell_material_group)).setOnCheckedChangeListener(materListener);
//            ((RadioGroup) view.findViewById(R.id.pop_shell_technics_group)).setOnCheckedChangeListener(techListener);
            propertyGridView = (MyGrideView) view.findViewById(R.id.pop_shell_technics_grid_view);
            propertyGridView.setOnItemClickListener(propetryItem);
            materialGridView = (MyGrideView) view.findViewById(R.id.pop_shell_material_grid_view);
            materialGridView.setOnItemClickListener(materialItem);

        }
        filterPop.showAsDropDown(filterLayout);

        //品牌
        if (brandAdapter == null) {
            brandAdapter = new PhoneShellBrandAdapter(getActivity(), brandList);
            brandGridView.setAdapter(brandAdapter);
        } else {
            brandAdapter.notifyDataSetChanged();
        }

        if (materialAdapter == null) {
            materialAdapter = new ShellPropertyAdapter(getActivity(), materialList);
            materialGridView.setAdapter(materialAdapter);
        } else {
            materialAdapter.notifyDataSetChanged();
        }
        if (propertyAdapter == null) {
            propertyAdapter = new ShellPropertyAdapter(getActivity(), technologyList);
            propertyGridView.setAdapter(propertyAdapter);
        } else {
            propertyAdapter.notifyDataSetChanged();
        }


    }

    /**
     * 网络请求品牌类型
     */
    public void requestBrandData() {
        brandUrl = ConfigAPI.PHONE_SHELL_FILTER + categoryId;
        cagyRequest = NoHttp.createJsonArrayRequest(brandUrl, RequestMethod.GET);
        cagyRequest.setCancelSign(brandUrl.hashCode());
        NoHttpCallBack.getInstance().add(getActivity(), brandUrl.hashCode(), cagyRequest, this, true, true);
    }

    private void reqProperty(String type) {
        propertyUrl = ConfigAPI.PHONE_SHELL_PROPERTY;
        Request<JSONArray> protRequest = NoHttp.createJsonArrayRequest(propertyUrl, RequestMethod.GET);
        protRequest.setCancelSign(propertyUrl.hashCode());
        NoHttpCallBack.getInstance().add(getActivity(), propertyUrl.hashCode(), protRequest, this, true, false);
    }


    private AdapterView.OnItemClickListener brandItemClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//            Tools.toastTools(getActivity(),"brand " + position);
            brandAdapter.setSelection(position);
            if (brandList.size() > 0) {
                brandAdapter.setSelection(position);

                PhoneShellBrandBean brand = brandList.get(position);
                if (modelMap.containsKey(brand.getId())) {
                    modelList = modelMap.get(brand.getId());
                    if (modelAdapter == null) {
                        modelAdapter = new PhoneShellBrandAdapter(getActivity(), modelList);
                        modelGridView.setAdapter(modelAdapter);
                    } else {
                        modelAdapter.notify(modelList);
                    }
                    modelAdapter.setSelection(0);
                    if (modelList.size()>0){
                        categoryName = modelList.get(0).getName();
                        categoryNum = modelList.get(0).getCategoryNum();
                    }
                    modelTitleTv.setVisibility(View.VISIBLE);
                } else {
                    categoryId = brand.getId();
                    requestBrandData();
                }
            }
        }
    };

    private AdapterView.OnItemClickListener modelItemClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (modelList != null && modelList.size() > 0) {
                modelAdapter.setSelection(position);
                PhoneShellBrandBean model = modelList.get(position);
                categoryName = model.getName();
                categoryNum = model.getCategoryNum();
            }
        }
    };

    private AdapterView.OnItemClickListener materialItem = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (materialList.size() > 0) {
                materialAdapter.setSelection(position);
                if (position == 0) {
                    sc_material = "";
                } else {
                    sc_material = materialList.get(position).getName();
                }
            }
        }
    };
    private AdapterView.OnItemClickListener propetryItem = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (technologyList.size() > 0) {
                propertyAdapter.setSelection(position);
                if (position == 0) {
                    sc_technology = "";
                } else {
                    sc_technology = technologyList.get(position).getName();
                }
            }
        }
    };

//    private RadioGroup.OnCheckedChangeListener materListener = new RadioGroup.OnCheckedChangeListener() {
//        @Override
//        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
//            switch (checkedId) {
//                case R.id.pop_shell_material_all_bt:
//                    sc_material = "全部";
//                    break;
//                case R.id.pop_shell_material_tpu_bt:
//                    sc_material = "TPU";
//                    break;
//                case R.id.pop_shell_material_pc_bt:
//                    sc_material = "PC";
//                    break;
//            }
//        }
//    };
//    private RadioGroup.OnCheckedChangeListener techListener = new RadioGroup.OnCheckedChangeListener() {
//        @Override
//        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
//            switch (checkedId) {
//                case R.id.pop_shell_technics_all_bt:
//                    sc_technology = "全部";
//                    break;
//                case R.id.pop_shell_technics_color_bt:
//                    sc_technology = "彩绘";
//                    break;
//                case R.id.pop_shell_technics_cameo_bt:
//                    sc_technology = "浮雕";
//                    break;
//                case R.id.pop_shell_technics_hand_drawing_bt:
//                    sc_technology = "手绘";
//                    break;
//            }
//        }
//    };

    public void requestGoods() {

        goodsUrl = ConfigAPI.PHONE_SHELL_GOODS + "sc_material=" + URLEncoder.encode(sc_material) + "&sc_technology=" + URLEncoder.encode(sc_technology)
                + "&sc_categoryNum=" + categoryNum + "&page=" + page + "&size=" + size;
        Request<JSONObject> goodsRequest = NoHttp.createJsonObjectRequest(goodsUrl, RequestMethod.GET);
        goodsRequest.setCancelSign(goodsUrl.hashCode());
        goodsRequest.addHeader("X-Authorization-MemberId", uid);
        NoHttpCallBack.getInstance().add(getActivity(), goodsUrl.hashCode(), goodsRequest, this, true, true);
    }

    @Override
    public void onSuccessed(int what, Response response) {
        int requestCode = response.responseCode();
        if (requestCode == 200) {
            if (what == brandUrl.hashCode()) {
                JSONArray jsonArray = (JSONArray) response.get();
                if (jsonArray.length() == 0) {
                    Tools.toastTools(getActivity(), "暂时还没有数据");
                    return;
                }
                List<PhoneShellBrandBean> mData = new ArrayList<>();
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object = jsonArray.optJSONObject(i);
                    int id = object.optInt("id");
                    String name = object.optString("name");
                    String categoryNum = object.optString("categoryNum");
                    PhoneShellBrandBean brandBean = new PhoneShellBrandBean(categoryNum, id, name);
                    mData.add(brandBean);
                }
                if (categoryId == 1) {
                    brandList.addAll(mData);

                } else {
                    modelList = mData;
                    modelMap.put(categoryId, mData);
                    if (modelAdapter == null) {
                        modelAdapter = new PhoneShellBrandAdapter(getActivity(), modelList);
                        modelGridView.setAdapter(modelAdapter);
                    } else {
                        modelAdapter.notify(modelList);
                    }
                    modelAdapter.setSelection(0);
                    if (modelList.size()>0){
                        categoryName = modelList.get(0).getName();
                        categoryNum = modelList.get(0).getCategoryNum();
                    }

                    modelTitleTv.setVisibility(View.VISIBLE);
                }


            } else if (what == goodsUrl.hashCode()) {
                listView.stopRefresh();
                listView.stopLoadMore();
                JSONObject json = (JSONObject) response.get();
                int totalPages = json.optInt("totalPages");
                if (totalPages - page > 1) {
                    //还有更多
                    listView.setPullLoadEnable(true);
                } else {
                    listView.setPullLoadEnable(false);
                }
                JSONArray goodsArray = json.optJSONArray("content");
                if (goodsArray != null && goodsArray.length() > 0) {
                    if (refresh) {
                        goodsList.clear();
                        refresh = false;
                    }

                    int length = goodsArray.length();
                    JSONObject item = null;
                    JSONObject goods = null;
                    ShellGoodsBean goodsBean = null;
                    for (int i = 0; i < length; i++) {
                        item = goodsArray.optJSONObject(i);
                        goodsBean = new ShellGoodsBean();
                        goodsBean.setMembersPrice(item.optDouble("membersPrice"));
                        goodsBean.setCategoryName(item.optString("categoryName"));
                        goodsBean.setKkmoveUrl(item.optString("kkmoveUrl"));
                        goods = item.optJSONObject("goods");
                        goodsBean.setId(goods.optString("id"));
                        goodsBean.setTitle(goods.optString("title"));
                        goodsBean.setImageUrl(goods.optString("imageUrl"));
                        goodsBean.setMaterial(goods.optString("material"));
                        goodsBean.setTechnology(goods.optString("technology"));
                        goodsBean.setPrice(goods.optDouble("price"));
                        goodsBean.setDefaultSalePrice(goods.optDouble("defaultSalePrice"));
                        goodsBean.setOnsale(goods.optBoolean("onsale"));
                        goodsBean.setGyNum(goods.optString("gyNum"));
                        goodsBean.setGoodsNum(goods.optString("goodsNum"));
                        goodsBean.setCategoryNum(goods.optString("categoryNum"));
                        goodsList.add(goodsBean);
                    }

                }else{
                    Tools.toastTools(getActivity(),"未筛选到数据");
                    goodsList.clear();
                }

                if (goodsAdapter == null) {
                    goodsAdapter = new PhoneShellAdapter(getActivity(), goodsList);
                    listView.setAdapter(goodsAdapter);
                } else {
                    goodsAdapter.notify(goodsList);
                }


            } else if (what == propertyUrl.hashCode()) {
                JSONArray jsonArray = (JSONArray) response.get();
                if (jsonArray.length() == 0) {
                    Tools.toastTools(getActivity(), "暂时还没有数据");
                    return;
                }
                //第一位添加全部
                PropertyBean bean = new PropertyBean();
                bean.setValid(true);
                bean.setType("工艺");
                bean.setName("全部");
                bean.setId(-1);
                technologyList.add(bean);
                //材质
                bean = new PropertyBean();
                bean.setValid(true);
                bean.setType("材质");
                bean.setName("全部");
                bean.setId(-1);
                materialList.add(bean);

                int length = jsonArray.length();
                JSONObject obj = null;
                for (int i = 0; i < length; i++) {
                    bean = new PropertyBean();
                    obj = jsonArray.optJSONObject(i);
                    String type = obj.optString("type");
                    bean.setId(obj.optInt("id"));
                    bean.setName(obj.optString("name"));
                    bean.setType(type);
                    bean.setValid(obj.optBoolean("valid"));
                    if ("工艺".equals(type)) {
                        technologyList.add(bean);
                    } else {
                        materialList.add(bean);
                    }
                }



            }
        } else {
            Tools.toastTools(getActivity(), response.getException().toString());
        }
    }

    @Override
    public void onFailed(int what, Response response) {
        Tools.toastTools(getActivity(), "连接超时！");
    }

    @Override
    public void onRefresh() {
        page = 0;
        refresh = true;
        requestGoods();
    }

    @Override
    public void onLoadMore() {
        page += 1;
        requestGoods();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (goodsList != null && goodsList.size() > 0 && i > 0) {
            ShellGoodsBean goodsBean = goodsList.get(i - 1);
            Intent intent = new Intent(getActivity(), ShellWebViewActivity.class);
            String kkmoveUrl = "http://www.kkmove.com/?shop=1915&ext_param={userId:" + uid + ",goodsId:" + goodsBean.getId() + ",isApp=true}&cate=" + goodsBean.getGoodsNum();
            intent.putExtra("webType", 0);
            intent.putExtra("kkmoveUrl", kkmoveUrl);
            intent.putExtra("goodsBean", goodsBean);
            startActivity(intent);

//            Intent intent = new Intent();
//            intent.setAction("android.intent.action.VIEW");
//            Uri content_url = Uri.parse("http://www.kkmove.com/?shop=1915&ext_param={userId:"+uid+",goodsId:"+goodsBean.getId()+",isApp=true}&cate=" + goodsBean.getGoodsNum());
//            intent.setData(content_url);
//            startActivity(intent);

        }

    }


}
